<template>
    <div class="container">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item>
                <el-date-picker :model="queryInfo.dateRange" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" @change="handleDateChange" clearable @clear="getActivityList" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getActivityList">查询</el-button>
            </el-form-item>
        </el-form>
        <div id="pieChartChannel" style="width: 2000px; height: 430px; margin-bottom: 20px;"></div>
        <div id="lineChartChannel" style="width: 1600px; height: 400px;"></div>
        <el-table :data="activityList" style="width: 100%">
            <el-table-column prop="name" label="渠道名称" width="180" />
            <el-table-column prop="count" label="线索数量" width="180" />
            <el-table-column prop="available" label="线索有效率" />
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { listChannel } from '../../../api/tienchin/analysis';
import { ElMessage } from 'element-plus';

const queryInfo = ref({
    pageNum: 1,
    pageSize: 10,
    dateRange: [],
    params: {
        beginTime: '',
        endTime: ""
    }
});
// 格式化日期为 YYYY-MM-DD HH:mm:ss
const formatDate = (date) => {
    if (!date) return '';
    const pad = (n) => (n < 10 ? '0' + n : n);
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
// 处理日期变化
const handleDateChange = (value) => {
    if (value && value.length === 2) {
        const [start, end] = value;

        // 确保开始时间早于结束时间
        if (start && end && start < end) {
            // 格式化 dateRange 中的日期
            queryInfo.value.dateRange = [formatDate(start), formatDate(end)];
            queryInfo.value.params.beginTime = formatDate(start); // 设置开始时间
            queryInfo.value.params.endTime = formatDate(end); // 设置结束时间
        } else {
            ElMessage.warning("结束时间必须晚于开始时间");
            queryInfo.value.dateRange = [];
            queryInfo.value.params.beginTime = '';
            queryInfo.value.params.endTime = '';
        }
    } else {
        queryInfo.value.dateRange = [];
        queryInfo.value.params.beginTime = '';
        queryInfo.value.params.endTime = '';
    }
};
const activityList = ref([]);

// ECharts 实例
const pieChartInstance = ref<echarts.ECharts | null>(null);
const lineChartInstance = ref<echarts.ECharts | null>(null);

// 图表的配置项
const pieChartOption = ref<echarts.EChartsOption>({
    title: {
        text: "活动总数分析",
        left: "center",
    },
    tooltip: {
        trigger: "item",
    },
    legend: {
        orient: "vertical",
        left: "left",
    },
    series: [
        {
            name: "活动分析",
            type: "pie",
            radius: "50%",
            data: [], // 数据动态加载
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                },
            },
        },
    ],
});

const lineChartOption = ref<echarts.EChartsOption>({
    title: {
        text: "活动有效率分析",
        left: "center",
    },
    tooltip: {
        trigger: "axis",
        axisPointer: {
            type: "line", // 鼠标跟随虚线
        },
        formatter: (params: any) => {
            // 自定义提示信息
            const data = params[0]; // 获取第一个点的信息
            const name = data.axisValue; // X 轴的名称
            const available = data.data; // Y 轴的值
            return `Name: ${name}<br/>Available: ${available}`;
        },
    },
    xAxis: {
        type: "category",
        data: [], // x轴的分类数据
    },
    yAxis: {
        type: "value",
    },
    series: {
        name: "活动线索有效率",
        type: "line",
        data: [], // 折线图的值
        smooth: true,
    }

});

// 初始化图表
const initCharts = () => {
    const pieDom = document.getElementById("pieChartChannel");
    const lineDom = document.getElementById("lineChartChannel");

    if (pieDom) pieChartInstance.value = echarts.init(pieDom);
    if (lineDom) lineChartInstance.value = echarts.init(lineDom);
};

const getActivityList = () => {
    listChannel(queryInfo.value).then((res: any) => {
        console.log(res);
        if (res.code === 200) {
            activityList.value = res.data;

            // **饼图数据**
            const pieData = activityList.value.map((item) => ({
                value: item.count,
                name: item.name,
            }));
            pieChartOption.value.series[0].data = pieData;

            // **折线图数据**
            const lineXAxisData = activityList.value.map((item) => item.name); // 使用 name 作为 X 轴数据
            const lineSeriesData = activityList.value.map((item) => item.available); // 使用 available 作为 Y 轴数据
            lineChartOption.value.xAxis.data = lineXAxisData;
            lineChartOption.value.series.data = lineSeriesData;
            // 渲染图表
            if (pieChartInstance.value) pieChartInstance.value.setOption(pieChartOption.value);
            if (lineChartInstance.value) lineChartInstance.value.setOption(lineChartOption.value);
        }
    });
};

onMounted(() => {
    getActivityList();
    initCharts();
});
</script>

<style scoped>
.container {
    padding: 20px;
}
</style>
